/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.znb.okdown.flutter

import android.content.Context
import android.os.Looper
import com.znb.okdown.flutter.android.view.AndroidViewPlugin
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.FlutterEngineGroup
import io.flutter.embedding.engine.dart.DartExecutor


/**
 * create by itz on 2024/1/17 15:52
 * desc :
 **/
class FlutterCacheManager {

    companion object {
        const val HOME = "home"
        const val MINE = "mine"
        const val SETTING = "setting"

        val instance = FlutterCacheHelper.flutterCacheManager
    }

    object FlutterCacheHelper {
        val flutterCacheManager = FlutterCacheManager()
    }


    fun preLoad(context: Context) {
        Looper.myQueue().addIdleHandler {
            initFlutterEngine(context, HOME)
            initFlutterEngine(context, MINE)
            initFlutterEngine(context, SETTING)
            false
        }
    }

    fun getCacheFlutterEngine(context: Context, moduleName: String): FlutterEngine? {
        var flutterEngine = FlutterEngineCache.getInstance()[moduleName]
        if (flutterEngine == null) {
            flutterEngine = initFlutterEngine(context, moduleName)
        }
        return flutterEngine
    }

    private fun initFlutterEngine(context: Context, moduleName: String): FlutterEngine? {
        val flutterEngine = FlutterEngine(context)
        //AndroidViewPlugin.registerWith(flutterEngine)
        flutterEngine.plugins.add(AndroidViewPlugin())
        //set route name
        flutterEngine.navigationChannel.setInitialRoute("/$moduleName")
        //init bridge
        FlutterBridge.instance.init(flutterEngine)
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )
        FlutterEngineCache.getInstance().put(moduleName, flutterEngine)
        return flutterEngine
    }
}